﻿//  Copyright (c) 2011 Ray Liang (http://www.dotnetage.com)
//  Licensed MIT: http://www.opensource.org/licenses/mit-license.php

using System.Collections.Generic;
using System.Linq;
using DNA.Mvc.Data.Entity;
using System.Data.Entity;

namespace DNA.Mvc.Management
{
    public class EntityLogRepository : EntityRepositoryBase<LogDB, EventLogEntry>, ILogRepository
    {
        public override IQueryable<EventLogEntry> All(out int total, int index = 0, int size = 50)
        {
            int skipCount = index * size;
            var _resultSet = skipCount == 0 ? DbSet.OrderByDescending(l => l.EventTimeUtc).Take(size) : DbSet.OrderByDescending(l => l.EventTimeUtc).Skip(skipCount).Take(size);
            total = dbSet.Count();
            return _resultSet.AsQueryable();
        }

        public EntityLogRepository(string nameOrConnectionString)
        {
            context = new LogDB(nameOrConnectionString);
            dbSet = this.Context.Set<EventLogEntry>();
            IsOwnContext = true;
        }

        public EntityLogRepository(LogDB dbContext)
        {
            context = dbContext;
            dbSet = this.Context.Set<EventLogEntry>();
            IsOwnContext = false;
        }

        public void Clear()
        {
            Context.Database.ExecuteSqlCommand("delete aspnet_WebEvent_Events");
        }
    }
}
